All files / src/app/api/dev/projects/[id] route.ts

0% Statements 0/213
100% Branches 0/0
0% Functions 0/1
0% Lines 0/213

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214                                                                                                                                                                                                                                                                                                                                                                                                                                           
export const dynamic = "force-dynamic";

/**
 * Dev Project Detail API
 * GET /api/dev/projects/[id] - Get a single project with stats
 * PATCH /api/dev/projects/[id] - Update a project
 * DELETE /api/dev/projects/[id] - Delete a project
 */

import { NextRequest, NextResponse } from 'next/server';
import { Session } from 'next-auth';
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse
} from "@/lib/api";
import type { AuthenticatedUser } from '@/lib/api/middleware/types';
import { prisma } from '@/lib/prisma';
import { UpdateDevProjectSchema } from '@/lib/validation/dev-ticket-schemas';
import { logger } from '@/lib/logging';

interface RouteParams {
  params: Promise<{ id: string }>;
}

async function handleGet(
  request: NextRequest,
  context: unknown
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;

  const project = await prisma.devProject.findUnique({
    where: { id },
    include: {
      lead: {
        select: { id: true, name: true, email: true, image: true }
      },
      milestones: {
        orderBy: { dueDate: 'asc' },
        include: {
          _count: { select: { tickets: true } }
        }
      },
      sprints: {
        orderBy: { startDate: 'desc' },
        take: 5,
        include: {
          _count: { select: { tickets: true } }
        }
      },
      _count: {
        select: {
          tickets: true,
          milestones: true,
          sprints: true
        }
      }
    }
  });

  if (!project) {
    throw ApiError.notFound('Project not found');
  }

  // Get ticket stats for this project
  const ticketStats = await prisma.devTicket.groupBy({
    by: ['status'],
    where: { projectId: id },
    _count: true
  });

  const stats = {
    byStatus: Object.fromEntries(ticketStats.map((s) => [s.status, s._count])),
    openTickets: ticketStats
      .filter((s) => ['OPEN', 'IN_PROGRESS', 'IN_REVIEW', 'TESTING', 'BLOCKED'].includes(s.status))
      .reduce((sum, s) => sum + s._count, 0),
    completedTickets: ticketStats
      .filter((s) => ['COMPLETED'].includes(s.status))
      .reduce((sum, s) => sum + s._count, 0)
  };

  return successResponse({
    ...project,
    stats
  });
}

async function handlePatch(
  request: NextRequest,
  context: unknown,
  session: Session,
  user: AuthenticatedUser
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;
  const body = await request.json();

  const validationResult = UpdateDevProjectSchema.safeParse(body);
  if (!validationResult.success) {
    throw ApiError.validation(
      'Validation failed',
      validationResult.error.flatten().fieldErrors
    );
  }

  // Check if project exists
  const existingProject = await prisma.devProject.findUnique({
    where: { id }
  });

  if (!existingProject) {
    throw ApiError.notFound('Project not found');
  }

  const data = validationResult.data;

  // If key is being changed, check uniqueness
  if (data.key && data.key !== existingProject.key) {
    const keyExists = await prisma.devProject.findUnique({
      where: { key: data.key }
    });

    if (keyExists) {
      throw ApiError.badRequest(`Project key "${data.key}" already exists`);
    }
  }

  // Verify lead exists if provided
  if (data.leadId) {
    const lead = await prisma.user.findUnique({
      where: { id: data.leadId },
      select: { id: true, role: true }
    });

    if (!lead || lead.role !== 'ADMIN') {
      throw ApiError.badRequest('Invalid project lead');
    }
  }

  // Update project
  const project = await prisma.devProject.update({
    where: { id },
    data,
    include: {
      lead: {
        select: { id: true, name: true, email: true, image: true }
      },
      _count: {
        select: {
          tickets: true,
          milestones: true,
          sprints: true
        }
      }
    }
  });

  logger.info(`Updated project ${project.key}`, {
    category: 'DEV_PROJECTS',
    projectId: id,
    userId: user.id,
    changes: Object.keys(data)
  });

  return successResponse(project);
}

async function handleDelete(
  request: NextRequest,
  context: unknown,
  session: Session,
  user: AuthenticatedUser
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const { id } = await (context as RouteParams).params;

  // Check if project exists
  const project = await prisma.devProject.findUnique({
    where: { id },
    include: {
      _count: { select: { tickets: true } }
    }
  });

  if (!project) {
    throw ApiError.notFound('Project not found');
  }

  // Prevent deletion if project has tickets
  if (project._count.tickets > 0) {
    throw ApiError.badRequest(
      `Cannot delete project with ${project._count.tickets} tickets. Move or delete tickets first.`
    );
  }

  // Delete project (cascades to milestones and sprints)
  await prisma.devProject.delete({
    where: { id }
  });

  logger.info(`Deleted project ${project.key}`, {
    category: 'DEV_PROJECTS',
    projectId: id,
    userId: user.id
  });

  return successResponse({ message: 'Project deleted successfully' });
}

export const GET = withErrorHandling(withAdmin(handleGet));
export const PATCH = withErrorHandling(withAdmin(handlePatch));
export const DELETE = withErrorHandling(withAdmin(handleDelete));